<?php
namespace app\common\widgets;

use app\models\dao\RoleAccess;
use app\models\dao\RoleNode;
use Yii;
use app\models\User;

class Rbac {

	public static $isSystem = false;

	public static $userId = '';

	public static $roleId = '';

	public function __construct($int_uid) {
		$userModel = User::findIdentity($int_uid);

		if('admin' == $userModel['username']) {
			self::$isSystem = true;
		}
		self::$userId = $userModel['id'];
		self::$roleId = $userModel['role_id'];
	}

	//检查当前用户是否需要认证
	static public function checkUserAccess() {
		return self::$isSystem;
	}

	static public function accessDecision() {
		$access_list = [];
		$roleMenu = [];
		$levelMenu = [];
		//获取用户所在用户组
		$nodeAccess = RoleAccess::find()->where(['role_id' => self::$roleId])->orderBy( 'node_id asc' )->asArray()->all();
//		echo "<pre>";print_r($nodeAccess);
//		echo "<pre>";print_r(self::$userId);
//		echo "<pre>";print_r(self::$roleId);

		if(!empty($nodeAccess)) {
			foreach($nodeAccess as $AccessList) {
				$roleNode = RoleNode::find()->where(['id' => $AccessList['node_id'], 'status' => 1, 'flag' => 1, 'level' => 2])->orderBy('sort asc')->asArray()->all();
//						echo "<pre>";print_r($roleNode);
				if(!empty($roleNode)) {

					foreach($roleNode as $key=> $nodeList) {

						$access_list[] = $nodeList['url'];
						if(2 == $nodeList['level']) {
							if(1 == $nodeList['is_show']) {
								$roleMenu[$nodeList['nav_id']][$key][$nodeList['id']] = $nodeList['parent_id'];
							} else {
								if(!in_array($nodeList['parent_id'], $levelMenu)) {
									$levelMenu[] = $nodeList['parent_id'];
									$roleMenu[$nodeList['nav_id']][$nodeList['parent_id']] = $nodeList['parent_id'];
								}
							}
						}
					}

				}
			}
		}

		return ['access_list' => $access_list, 'roleMenu' => $roleMenu];
	}
}